package com.googlecode.jtoy.patterns.templatemethod;

/**
 * 模板方法模式
 * 把相同的逻辑抽象成模板
 * 
 * @author shangxj
 * @date Jun 20, 2011 12:54:38 PM
 */
public abstract class TemplateMethodBubbleSorter {

	private int operations = 0;
	protected int length = 0;

	protected int doSort() {

		operations = 0;
		if (length <= 1) return operations;

		for (int nextToLast = length - 2; nextToLast >= 0; nextToLast--)
			for (int index = 0; index <= nextToLast; index++) {
				if (outOfOrder(index)) {
					swap(index);
				}
				operations++;
			}

		return operations;
	}

	protected abstract void swap(int index);

	protected abstract boolean outOfOrder(int index);
}
